package user

import (
	"context"
	"errors"
	"gitee.com/zhangyu520cw/basic-go/webook/internal/domain"
	"gitee.com/zhangyu520cw/basic-go/webook/internal/repository"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

var (
	ErrInvalidUserOrPassword = errors.New("invalid user or password")
	ErrDuplicateEmail        = repository.ErrDuplicateEmail
)

func (svc *UserServices) Login(ctx context.Context, email string, password string) (domain.User, error) {
	u, err := svc.repo.FindByEmail(ctx, email)
	if err == repository.ErrRecordNotFound {
		return domain.User{}, ErrInvalidUserOrPassword
	} else if err != nil {
		return domain.User{}, err
	}
	err = bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	if err != nil {
		return domain.User{}, err
	}
	return u, nil
}

func (svc *UserServices) FindById(ctx *gin.Context, uid int64) (domain.User, error) {
	return svc.repo.FindById(ctx, uid)
}

func (svc *UserServices) SignUp(ctx *gin.Context, u domain.User) error {
	pwd := []byte(u.Password)
	encryptedPwd, err := bcrypt.GenerateFromPassword(pwd, bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	u.Password = string(encryptedPwd)
	return svc.repo.Create(ctx, u)
}

func (svc *UserServices) UpdateNonSensitiveInfo(ctx *gin.Context, user domain.User) error {
	return svc.repo.UpdateNonZeroFields(ctx, user)
}
